package com.leaf.lowcode.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.leaf.lowcode.API.AppointmentApi;
import com.leaf.lowcode.entity.VisitRecordInfo;
import com.leaf.lowcode.entity.VisitRecordRequest;
import com.leaf.lowcode.mapper.VisitRecordMapper;
import com.leaf.lowcode.utils.RegularInstance;
import com.leaf.lowcode.utils.StringUtil;
import com.tencent.welink.iot.SubDeviceDTO;
import com.tencent.welink.iot.WelinkHttp;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class VisitDataRecorder {
    @Autowired
    private VisitRecordMapper visitRecordMapper;

    private static final Logger logger = LogManager.getLogger(VisitDataRecorder.class);

    //private static final String TOKEN_OVERTIME_KEYWORD = "token超时";
	private static final int WELINK_MODEL_ID = 200273;
    private static final String TIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ssZZ";

    private static final long TEN_MINUTES_DURATION = 600000L;

    private final String[] inDoors = {"612ecaab219e47d78285d811003f60ea", "6374c3364b23405d8f228e178013fc3a", "8ecde7abeb09493daec4b7960176f8e4", "b815be8dcf4440c8a4ce3c0a483c19c2", "c9eb8fda77c545ff94fb36e6319e2cbe"};
    private final String[] outDoors = {"28dc15a5f71846e0975ab3d8ef24f011", "67068117ec7e4743b23820048bc3c44a", "965d398225db438f9e4b72aaa50e9488", "e8d3c6c3e32e4af8a9d298e1ab483487", "d618ce515ce345e9a3d16ffe16f74231"};

    private final Map<String, String> doors = new HashMap<>();

    public VisitDataRecorder() {
        doors.put("612ecaab219e47d78285d811003f60ea", "1F-西侧1-进门_门_1");
        doors.put("6374c3364b23405d8f228e178013fc3a", "1F-中间-进门_门_1");
        doors.put("8ecde7abeb09493daec4b7960176f8e4", "1F-东侧1-进门_门_1");
        doors.put("b815be8dcf4440c8a4ce3c0a483c19c2", "1F-西侧2-进门_门_1");
        doors.put("c9eb8fda77c545ff94fb36e6319e2cbe", "1F-东侧2-进门_门_1");

        doors.put("28dc15a5f71846e0975ab3d8ef24f011", "1F-中间-出门_门_1");
        doors.put("67068117ec7e4743b23820048bc3c44a", "1F-东侧2-出门_门_1");
        doors.put("965d398225db438f9e4b72aaa50e9488", "1F-西侧1-出门_门_1");
        doors.put("e8d3c6c3e32e4af8a9d298e1ab483487", "1F-东侧1-出门_门_1");
        doors.put("d618ce515ce345e9a3d16ffe16f74231", "1F-西侧2-出门_门_1");
    }

    /**
     * 定时获取访客门禁进出记录
     */
    @Scheduled(initialDelay = 60 * 1000, fixedRate = 60 * 2000)
    public void fetchVisitRecords() {
        printInfo("Starting fetching visit records...");
        AppointmentApi appointmentApi = new AppointmentApi();
        VisitRecordRequest request = new VisitRecordRequest();
        request.setPageNo(1);
        request.setPageSize(100);
        long now = System.currentTimeMillis();
        Date startTime = new Date(now - TEN_MINUTES_DURATION);
        Date endTime = new Date(now);
        request.setEventTimeBegin(DateFormatUtils.format(startTime, TIME_PATTERN));
        request.setEventTimeEnd(DateFormatUtils.format(endTime, TIME_PATTERN));
        for (String device : inDoors) {
            request.setResourceCode(device);
            printInfo("Fetching in-door visit records for: " + device);
            String retStr = appointmentApi.getVisitRecords(request);
            handleRecords(retStr, device, true);
        }

        for (String device : outDoors) {
            request.setResourceCode(device);
            printInfo("Fetching out-door visit records for: " + device);
            String retStr = appointmentApi.getVisitRecords(request);
            handleRecords(retStr, device, false);
        }
    }

    private void handleRecords(String records, String resourceCode, boolean in) {
        JSONObject jsonObject = JSONObject.parseObject(records);
        String code = (String) jsonObject.get("code");
        if (!code.equals("0")) {
            printError("get visit records of " + resourceCode + " failed, return code: " + code);
            return;
        }
        JSONArray visitRows = (JSONArray) ((JSONObject) jsonObject.get("data")).get("rows");
        int type = in ? 0 : 1;
        for (Object row : visitRows) {
            JSONObject visitRow = (JSONObject) row;
            String orderId = (String) visitRow.get("orderId");
            String eventTime = (String) visitRow.get("eventTime");
            String rowId = visitRecordMapper.selectId(orderId, resourceCode, eventTime);
            if (rowId == null) {
                //new record, store to database
                printInfo("New visit record, store to database. " + resourceCode + "-" + orderId);
                VisitRecordInfo visitInfo = new VisitRecordInfo();
                visitInfo.setOrderId(orderId);
                visitInfo.setType(type);
                visitInfo.setResourceCode(resourceCode);
                visitInfo.setEventTime(eventTime);
                visitInfo.setVisitorName((String) visitRow.get("visitorName"));
                visitInfo.setReceptionistId((String) visitRow.get("beVisitPersonId"));
                visitInfo.setReceptionistName((String) visitRow.get("beVisitPersonName"));
                visitInfo.setCardType((Integer) visitRow.get("cardType"));
                visitInfo.setCardNum((String) visitRow.get("cardNum"));
                visitInfo.setEventId((String) visitRow.get("eventId"));
                visitInfo.setEventName((String) visitRow.get("eventName"));
                visitInfo.setPhoneNum((String) visitRow.get("phoneNum"));
                visitInfo.setCarNum((String) visitRow.get("carNumber"));

                visitRecordMapper.insert(visitInfo);

                //report to WeiLink
                printInfo("New visit record, report to WeLink. " + resourceCode + "-" + orderId);
                reportToWeLink(visitInfo);
            }
        }
    }

    private void reportToWeLink(VisitRecordInfo visitInfo) {
        List<SubDeviceDTO> subDeviceDTOList = RegularInstance.subDeviceDTOList;
        if (null == subDeviceDTOList) {
            printError("Get device list failure!");
        } else {
            for (SubDeviceDTO dto : subDeviceDTOList) {
                String sn = dto.getSn();
                if (visitInfo.getResourceCode().equals(sn)) {
                    printInfo("Reporting WeLink data for sn: " + sn);
                    JSONObject standardData = new JSONObject();
                    standardData.put("reportTs", System.currentTimeMillis());
                    JSONObject profile = new JSONObject();
                    profile.put("modelId", WELINK_MODEL_ID);
                    profile.put("appType", "visitor");
                    profile.put("pioCode", "w0717006");
                    standardData.put("profile", profile);

                    JSONObject events = new JSONObject();
                    JSONObject event = new JSONObject();
                    event.put("alarmLevel", 1);
                    event.put("eventType", 0);
                    event.put("eventTs", System.currentTimeMillis());
                    event.put("describe", "");
                    event.put("orderId", visitInfo.getOrderId());
                    event.put("visitorUserName", StringUtil.strToUnicode(visitInfo.getVisitorName()));
                    event.put("arriveTime", visitInfo.getEventTime());
                    event.put("label", visitInfo.getType());
                    event.put("svrIndexCode", visitInfo.getResourceCode());
                    event.put("beVisitUserName", StringUtil.strToUnicode(visitInfo.getReceptionistName()));

                    String doorName = doors.get(visitInfo.getResourceCode());
                    if (null == doorName) {
                        printError("wrong door resource code: " + visitInfo.getResourceCode());
                        doorName = "";
                    }
                    event.put("doorName", StringUtil.strToUnicode(doorName));
                    event.put("carNum", visitInfo.getCarNum());
                    event.put("visitorUserPhone", visitInfo.getPhoneNum());

                    events.put("inout", event);

                    standardData.put("events", events);
                    standardData.put("properties", new JSONObject());
                    String devRunEvent = JSONObject.toJSONString(standardData, SerializerFeature.WriteMapNullValue);

                    WelinkHttp wh = new WelinkHttp(RegularInstance.registerData1, RegularInstance.loginData);
                    try {
                        printInfo("Start report to WeLink...");
                        wh.sendMessage(RegularInstance.loginData.load(), 80000, Long.parseLong(dto.getDin()), devRunEvent, true);
                        printInfo("Reported to WeLink.");
                    } catch (MqttException e) {
                        printError("Report to WeLink failure! " + e.getMessage());
                        e.printStackTrace();
                    }

                    break;
                }
            }
        }
    }

    private void printInfo(String info) {
        logger.info(info);
        System.out.println("[Info] " + info);
    }

    private void printError(String error) {
        logger.error(error);
        System.out.println("[Error] " + error);
    }

    /*
    private JSONObject runRequest(String url, String params, HttpMethod method) throws Exception {
        // 公钥
        String publicKey = new RsaUtil("rsapublic.xml").Key();
        EncrypRSA rsa = new EncrypRSA();
        byte[] ciphertextPublic = rsa.encrypt(publicKey, params, "PUBLIC");
        String jsonParams = new String(Base64.getEncoder().encode(ciphertextPublic));

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>();
        paramsMap.add("json", jsonParams);
        HttpEntity<MultiValueMap<String, String>> requestData = new HttpEntity<>(paramsMap, headers);

        String urlWithToken = url + getToken();
        ResponseEntity<String> responseEntity = restTemplate.exchange(urlWithToken, method, requestData, String.class);
        String body = responseEntity.getBody();
        if (body.contains(TOKEN_OVERTIME_KEYWORD)) {
            urlWithToken = url + getToken();
            responseEntity = restTemplate.exchange(urlWithToken, method, requestData, String.class);
            body = responseEntity.getBody();
        }

        JSONObject jsonObj = JSON.parseObject(body);

        return jsonObj;
    }

    private String getToken() {
        QueryToken queryToken = new QueryToken();
        String token = queryToken.execute();
        System.out.println("token: " + token);

        return token;
    }
    */

    /*
    public static void main(String[] args) {
        VisitDataRecorder recorder = new VisitDataRecorder();
        recorder.fetchVisitRecords();
    }
     */
}
